﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml;

namespace ontheroad
{
    public partial class intsignlist : PhoneApplicationPage
    {
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            getFavVMS();
        }

        public intsignlist()
        {
            InitializeComponent();
            getVMS();
        }

        private void viewintsignbut_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            string nameth = "";
            Button t = sender as Button;
            foreach (trafficVMS i in linkList)
            {
                if (i.vmsNo.Equals(t.Tag))
                    nameth = i.vmsThaiName;
            }
            NavigationService.Navigate(new Uri("/imgresultpage.xaml?id=" + t.Tag + "&title=" + nameth + "&type=2", UriKind.RelativeOrAbsolute));
        }

        private void viewfavintsignbut_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }

        List<trafficVMS> linkList;

        private void searchintsignbut_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            setSearchIntSign();
                
            
        }

        private void setSearchIntSign()
        {
            string roadName = searchintsigntxtbox.Text;

            List<trafficVMS> cfc = new List<trafficVMS>();

            for (int i = 0; i < linkList.Count; i++)
                if (linkList[i].vmsName.Contains(roadName) || linkList[i].vmsThaiName.Contains(roadName))
                    cfc.Add(linkList[i]);
            if (cfc.Count == 0)
            {
                MessageBox.Show("ไม่พบตำแหน่งของป้ายจราจรอัจฉริยะที่ต้องการ");
            }
            else
            {
                cctvlistbox.ItemsSource = cfc;
            }
        }

        private void getFavVMS()
        {
            List<int> idList = new List<int>();
            try
            {
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("intsigntest.xaml", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {    //Visualize the text data in a TextBlock text
                    XElement eld = XElement.Parse(reader.ReadToEnd());
                    //MessageBox.Show("");
                    while (eld.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((eld.FirstNode as XElement).Value);
                        (eld.FirstNode as XElement).Remove();
                        idList.Add(idAdd);
                    }
                }
            }
            catch (Exception)
            {
            }

            List<trafficVMS> vmsFav = new List<trafficVMS>();

            for (int i = 0; i < linkList.Count; i++)
                if (idList.Contains(Convert.ToInt32(linkList[i].vmsNo)))
                    vmsFav.Add(linkList[i]);

            if (vmsFav.Count != 0)
                noticeMsgFav.Visibility = Visibility.Collapsed;
            else
                noticeMsgFav.Visibility = Visibility.Visible;

            waitScr.Visibility = Visibility.Collapsed;

            cctvfavlistbox.ItemsSource = vmsFav;
        }

        private void getVMS()
        {
            WebClient wcf = new WebClient();
            linkList = new List<trafficVMS>();
            Uri uri = new Uri("http://api.traffy.in.th/apis/apitraffy.php?format=XML&api=getVMS&key="
                + App.traf.sessionkey + "&appid=" + App.traf.appid);
            wcf.DownloadStringAsync(uri);
            wcf.DownloadStringCompleted += (s, e) =>
            {
                XElement elm;
                try
                {
                    elm = XElement.Parse(e.Result);
                }

                catch (WebException)
                {
                    MessageBox.Show("Please check your internet connection.");
                    NavigationService.GoBack();
                    return;
                }
                catch (Exception)
                {
                    MessageBox.Show("Server connection failed, Please wait a minute and try again.");
                    NavigationService.GoBack();
                    return;
                }
                while (elm.FirstNode != null)
                {
                    trafficVMS vms = new trafficVMS();
                    vms.vmsNo = (elm.FirstNode as XElement).FirstAttribute.Value;
                    vms.vmsName = (elm.FirstNode as XElement).FirstAttribute.NextAttribute.Value;
                    vms.vmsThaiName = (elm.FirstNode as XElement).FirstAttribute.NextAttribute.NextAttribute.Value;
                    vms.vmsUrl = (((elm.FirstNode as XElement).FirstNode as XElement).NextNode as XElement).Value;
                    linkList.Add(vms);


                    elm.FirstNode.Remove();
                }
                cctvlistbox.ItemsSource = linkList;
                getFavVMS();
            };
        }

        private void delfavbut_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxResult m = MessageBox.Show("delete from favorites", "Confirm ?", MessageBoxButton.OKCancel);
            if (m == MessageBoxResult.OK)
            {
                int id = Convert.ToInt32((sender as Image).Tag.ToString());

                string fileName = "intsigntest.xaml";
                XElement elm;
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    string readString = reader.ReadToEnd();
                    elm = XElement.Parse(readString);
                }


                List<int> idList = new List<int>();
                while (elm.FirstNode as XElement != null)
                {
                    int idAdd = Convert.ToInt32((elm.FirstNode as XElement).Value);
                    (elm.FirstNode as XElement).Remove();
                    if (idAdd != id)
                        idList.Add(idAdd);
                }

                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                    {
                        writer.WriteStartElement("intsign");
                        for (int i = 0; i < idList.Count; i++)
                        {
                            writer.WriteStartElement("id");
                            writer.WriteString(idList[i].ToString());
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                        writer.Flush();
                    }
                }
                getFavVMS();
            }
        }

        private void searchintsigntxtbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (e.Key == Key.Enter)
                setSearchIntSign();
        }
    }
}
